package itsm.isperp.module.service.customer;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppDepartment;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.repository.customer.CusCustomerMapper;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.app.AppUserService;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class CusCustomerService extends BaseService<CusCustomer> {

	@Autowired
	protected CusCustomerMapper cusCustomerMapper;

	@Override
	public CusCustomerMapper getRepository() {
		return this.cusCustomerMapper;
	}

	
	public List<Map<String, Object>> getCustomerCiCount() {
    JqGridRequest req = new JqGridRequest();
    req.isPageable(false);
    req.setSelectColumns("id", "name", "COUNT(ci_id) AS count_id ");
    req.setGroupBy("id,name");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    IUser curUser=ContextHolder.getLoginUser();
    String userName=curUser.getUsername();
    AppUser u = appUserService.findByUsername(userName);
    if (u.isAreCustomer()) {
      String customerId = u.getCustomerId();
      req.addFilterRule("id", JqGridFilterRuleOp.eq,
          customerId);
    } else {

    }
    return this.getRepository().findCustomerCi(req);
  }
	
	public CusCustomer getCompanyCustomer()
	{
		JqGridRequest request = new JqGridRequest();
		request.addFilterRule("category", JqGridFilterRuleOp.eq,
				"company");
		return this.cusCustomerMapper.findAllByRequest(request).get(0);
	}
	
	public CusCustomer findOneByNameOrFullname(String name)
  {
    JqGridRequest request = new JqGridRequest();
    request.setSearchString(" name='"+name+"' or fullname='"+name+"'");
    List<CusCustomer> list=this.cusCustomerMapper.findAllByRequest(request);
    if(list.size()>0)
      return list.get(0);
    else
      return null;
  }
	
	public void saveCustomerWithCreateDept(String id,String name)
  {
    String cusDeptId=id;
    String cusDeptName=name;
    String cusDeptParentId="";
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    String sql="select * from app_department where name='客户'";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
    if(list.size()>0)
    {
      cusDeptParentId=list.get(0).get("id").toString();
    }
    String sql3="insert into app_department(id,name,parent_id) values('"+cusDeptId+"','"+cusDeptName+"','"+cusDeptParentId+"')";
    jdbcTemplate.execute(sql3);
    jdbcTemplate.execute("call sp_treenode_rebuild('app_department')");
   
    CusCustomer tempCusCustomer=new CusCustomer();
    tempCusCustomer.setDepartmentId(cusDeptId);
    tempCusCustomer.setDepartmentName(cusDeptName);
    tempCusCustomer.setId(cusDeptId);
    tempCusCustomer.setName(cusDeptName);
    tempCusCustomer.setFullname(cusDeptName);
    tempCusCustomer.setCode(cusDeptName);
    tempCusCustomer.setCategory("customer");
    this.saveOrUpdate(tempCusCustomer);
  }
	
	public Map<String,Object> getCustomerByRelateDeptId(String deptId)
	{
	  JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
	  AppDepartmentService appDepartmentService = ContextHolder.getSpringBean("appDepartmentService");
    String sql = "SELECT id,category,name FROM cus_customer";
    if (StringUtils.isEmpty(deptId)) {
      return null;
    } else {

      AppDepartment dept = appDepartmentService.findOne(deptId);

      String[] ps = dept.getTreenodePath().split("/");
      String dIds = "";
      for (String s : ps) {
        if (StringUtils.isNotEmpty(s)) {

          dIds += ",'" + s + "'";
        }
      }
      sql += "  WHERE department_id IN(" + dIds.substring(1) + ")";

    }
    try {
      return jdbcTemplate.queryForMap(DialectFactory.getDialect()
          .getLimitString(sql));
    } catch (Exception e) {
      return null;
    }
	}
	
	
}
